<script setup lang="ts">
import { nextTick, ref, watch } from 'vue'
import { useBaseApi } from '@/api/base'
import type {
  BusinessUIFormType,
  BusinessUIQueryColumnType,
  BusinessUITableType,
  DicType
} from '@/types/custom'
import { ElMessage } from 'element-plus'

import TemplateForm from '@/views/components/form/TemplateForm.vue'
import { useRoute } from 'vue-router'

const { get_business_ui } = useBaseApi()

const route = useRoute()

const modelValue = defineModel<string | undefined>()

interface Props {
  item?: BusinessUIQueryColumnType
  insert?: boolean
  params?: TypedAny
  formId?: string
}

const props = defineProps<Props>()

const emit = defineEmits(['fetch'])
const loading = ref(false)

const currentFormId = ref('')
// 表单
const formRef = ref()
// 编辑模式
const isForm = ref(true)
// 表单
// const formParams = ref<TypedAny>({})
// 表单
const uiForm = ref<BusinessUIFormType | undefined>()
// 表格
const uiTable = ref<BusinessUITableType | undefined>()
// 表单字典
const dicTable = ref<DicType[]>([])

/**
 * 格式化默认参数
 * @param id
 */
const onDefaultFetch = async (id?: string) => {
  if (!id) return
  loading.value = true
  return get_business_ui(id, true)
    .then(({ data }) => {
      const dic_table = data.dic_table || []
      const ui_table = data.ui_table
      const ui_form = data.ui_form
      if (ui_form) {
        // 参数
        uiForm.value = ui_form
        // formParams.value = ui_form?.default_value_parse || {}
        // onFetch()
        if (ui_form.api && props.params && !props.formId && props.params.id) {
          currentFormId.value = props.params.id
        } else if (props.params && props.item) {
          currentFormId.value = props.params[props.item.field]
        }
      }
      if (ui_table) uiTable.value = ui_table

      dicTable.value = dic_table

      onFetchForm()
    })
    .finally(() => (loading.value = false))
}

const onFetch = () => {
  nextTick(() => {
    loading.value = true
    formRef.value.onFetch().finally(() => (loading.value = false))
  })
}

/**
 * 业务表单提交
 */
const onSave = () => {
  loading.value = true
  if (formRef.value) {
    return formRef.value
      .submitForm()
      .then(() => {
        emit('fetch')
        ElMessage.success('保存成功')
      })
      .finally(() => (loading.value = false))
  } else {
    return Promise.resolve()
  }
}

const onFetchForm = () => {
  nextTick(() => {
    formRef.value?.onFetch()
  })
}

watch(
  modelValue,
  (id) => {
    console.log('keyField')
    if (!modelValue.value && route.meta.id) modelValue.value = route.meta.id
    // 默认模式
    onDefaultFetch(id)
  },
  { immediate: true }
)

watch(
  () => props.formId,
  (value) => {
    if (value && !currentFormId.value) {
      currentFormId.value = value
      onFetchForm()
    }
  }
)

defineExpose({ onSave })
</script>

<template>
  <TemplateForm
    v-if="uiForm"
    ref="formRef"
    :is-form="isForm"
    v-model="currentFormId"
    :params="params"
    :ui-form="uiForm"
    :ui-table="uiTable"
    :dic-table="dicTable"
    @fetch="onFetch"
    :class="[route.meta.id ? 'base-bg-color pa10' : '']"
  />
</template>
